package Aleehot100;

import C017.main;

import java.util.HashMap;

/**
 * ClassName: c10
 * Package: Aleehot100
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/5/23 22:11
 * @Version 1.0
 * @Since 1.0
 */
public class c10 {
    public static void main(String[] args) {
        int[] arr = {1,1,1};
        int k = 2;
        System.out.println(subarraySum(arr, k));
    }


    /**
     * @param nums
     * @param k
     * @return
     */
    public static int subarraySum(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] sum = getSum(nums);
        map.put(0, 1);
        int res = 0;
        for (int i = 0; i < sum.length; i++) {
            if (map.containsKey(sum[i] - k)) {
                res += map.get(sum[i] - k);
            }
            map.put(sum[i], map.getOrDefault(sum[i], 0) + 1);
        }

        return res;
    }


    /**
     * 获取前缀和
     *
     * @param arr
     * @return
     */
    public static int[] getSum(int[] arr) {
        int[] sum = new int[arr.length];
        sum[0] = arr[0];
        for (int i = 1; i < arr.length; i++) {
            sum[i] = sum[i- 1] + arr[i];
        }
        return sum;
    }
}
